package com.ly.controller;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.github.pagehelper.PageInfo;
import com.ly.bean.*;
import com.ly.service.OrderDetailService;
import com.ly.service.OrderService;
import com.ly.service.ProductService;
import com.ly.service.UserService;
import com.ly.util.AlipayConfig;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @author 李岩
 * @date 2021/12/14-15:04
 * @describe
 */
@Controller
@RequestMapping("/order/")
public class OrderController {
    private final Logger logger= LoggerFactory.getLogger(OrderController.class);
    private OrderController(){
        System.out.println("OrderController   的controller层");
    }
    @Reference(url = "dubbo://localhost:20884")
    private OrderService orderService;
    @Reference(url = "dubbo://localhost:20884")
    private OrderDetailService orderDetailService;
    @Reference(url = "dubbo://localhost:20882")
    private UserService userService;
    @Reference(url = "dubbo://localhost:20851")
    private ProductService productService;

    @RequestMapping("addOrder")
    public void addOrder(@RequestParam List<Integer> pids, EasybuyOrder order, @CookieValue(required = false) String uuid,
                           HttpServletRequest request, HttpServletResponse response){
        try {
            logger.info("添加订单  "+order);
            //获取登录用户的信息
            EasybuyUser loginUser = userService.findUserByRedis(uuid);
            //如果未登录 调转到登录界面
            if (loginUser==null){
                System.out.println("未登录");
            }
            //如果不登录 从redis中获取 确定购买的商品信息集合
            List<EasybuyOrderDetail> orderDetailList = new ArrayList<>();
            for (Integer pid : pids) {
                CarItem item = productService.findOrderCarItemFromRedis(loginUser.getId(), pid);
                EasybuyOrderDetail orderDetail = new EasybuyOrderDetail();
                orderDetail.setCost(item.getBuyNum() * item.getEasybuyProduct().getPrice());
                orderDetail.setProductid(item.getEasybuyProduct().getId());
                orderDetail.setQuantity(item.getBuyNum());
                orderDetailList.add(orderDetail);
            }
            order.setCreatetime(new Date());
            System.out.println("order  "+order);
            //添加订单  返回订单的id
            int orderId = orderService.insert(order, orderDetailList);
            //订单添加成功后 把购物车里的该商品信息删除
            for (Integer pid : pids) {
                productService.deleteProductCarItemFromRedis(loginUser,pid);
            }
            //如果这是一个新的地址 需要保存到地址表中


            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

            //商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = String.valueOf(orderId);
            //付款金额，必填
            String total_amount = String.valueOf(order.getCost());
            //订单名称，必填
            String subject = order.getLoginname()+order.getUseraddress();
            //商品描述，可空
            String body = null;

            alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                    + "\"total_amount\":\""+ total_amount +"\","
                    + "\"subject\":\""+ subject +"\","
                    + "\"body\":\""+ body +"\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            //请求
            String result = alipayClient.pageExecute(alipayRequest).getBody();

            response.setContentType("text/html; charset=utf-8");
            response.getWriter().write(result);
           // return "BuyCar";
        } catch (Exception e) {
            logger.error("添加订单出现异常",e);
        }
        //return "error";
    }

    @RequestMapping("return_url")
    public String return_url(HttpServletRequest request) {
        try {

            //获取支付宝GET过来反馈信息
            Map<String,String> params = new HashMap<String,String>();
            Map<String,String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }

            boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

            //——请在这里编写您的程序（以下代码仅作参考）——
            if(signVerified) {
                //商户订单号
                String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

                //支付宝交易号
                String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

                //付款金额
                String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
                EasybuyOrder order = new EasybuyOrder();
                order.setSerialnumber(trade_no);
                order.setCost(Double.valueOf(total_amount));
                order.setId(Integer.valueOf(out_trade_no));
                request.setAttribute("order",order);
                //修改数据库中订单的状态
                orderService.updateOrderPayStatus(Integer.valueOf(out_trade_no),trade_no);
                return "BuyCar_Three";
            }else {
                //out.println("trade_no:"+trade_no+"<br/>out_trade_no:"+out_trade_no+"<br/>total_amount:"+total_amount);
                System.out.println("验签失败");
                //out.println("验签失败");
            }
            //——请在这里编写您的程序（以上代码仅作参考）——

        } catch (Exception e) {
           logger.error("验签出现异常   "+e);
        }
        return "error";
    }

    //根据登录的用户id获取该用户的订单信息
    @RequestMapping("selectOrderByUserId")
    public String selectOrderByUserId(@CookieValue(required = false) String uuid,Integer pageNum, Model model){

        try {
            logger.info("根据登录的用户id获取该用户的订单信息 "+pageNum);
            //获取登录用户的信息
            EasybuyUser loginUser = userService.findUserByRedis(uuid);
            if (loginUser==null){
                return "redirect:/login.html";
            }
            PageInfo<EasybuyOrder> pageInfo = orderService.selectOrderByUserId(loginUser.getId(),pageNum);
            model.addAttribute("pageInfo",pageInfo);

            return "Member_Order";
        } catch (Exception e) {
            logger.error("根据登录的用户id获取该用户的订单信息 出现异常 "+e);
        }
        return "error";
    }
    //根据订单id获取订单详情
    @RequestMapping("selectOrderDetailsByorderId")
    @ResponseBody
    public Result selectOrderDetailsByorderId(@RequestParam Integer orderId, Model model){

        try {
            logger.info("根据订单id获取订单详情 "+orderId);
            List<EasybuyOrderDetail> detailList = orderDetailService.selectOrderDetailsByorderId(orderId);
            return Result.getResult(true,200,"查询订单详情成功 ",detailList);
        } catch (Exception e) {
            logger.error("根据订单id获取订单详情 出现异常 "+e);
        }
        //return "error";
        return Result.getResult(false,444,"查询订单详情失败 ",null);
    }
}
